/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.bsuir.bbs.commands;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import by.bsuir.bbs.additional.SecuritySettings;
import by.bsuir.bbs.dao.UserJpaController;
import by.bsuir.bbs.dao.exceptions.RollbackFailureException;
import by.bsuir.bbs.persistence.User;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Администратор
 */
public class RegCommand implements Command{

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //requesting parameters from register form
        String page;
        String login = request.getParameter("login");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String contacts = request.getParameter("contacts");
        String city = request.getParameter("city");
        String lastName = request.getParameter("lastName");
        String firstName = request.getParameter("firstName");
        String middleName = request.getParameter("middleName");
        
        UserJpaController userJC =  new UserJpaController();
        List list = userJC.findUserByLogin(login);
        if (!list.isEmpty()) { //if exist(list not empty)
            request.setAttribute("message", "qweqweq");
            page = "/register.jsp";
        }
        else {
            try {
                User user = new User();
                user.setLogin(login);
                user.setFirstName(firstName);
                user.setLastName(lastName);
                user.setMiddleName(middleName);
                user.setCity(city);
                user.setContact(contacts);
                user.setAccess(0);
                user.setEmail(email);
                
                String encrypted_pass = SecuritySettings.encrypt(password);
                user.setPassword(encrypted_pass);
                userJC.create(user);
            } catch (RollbackFailureException ex) {
                Logger.getLogger(RegCommand.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(RegCommand.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return "/index.jsp";
    }
    
}
